package c04.biasedlock;

import lombok.extern.slf4j.Slf4j;

import java.util.Vector;

/*
批量重偏向

偏向锁默认是延迟生效的，程序启动时不会立即生效，如果想避免延迟，可以加VM参数禁用延迟：
-XX:BiasedLockingStartupDelay=0

偏向锁适用于很少发生竞态条件的情况，对于确定一般情况下都会发生竞态条件的应用场景，可以禁用偏向锁
-XX:-UseBiasedLocking
 */
@Slf4j(topic = "c.BatchBiasedRedirect")
public class BatchBiasedRedirect {
    static class Dog {

    }

    public static void main(String[] args) throws InterruptedException {
        Vector<Dog> list = new Vector<>();

        Thread t1 = new Thread(() -> {
            for (int i = 1; i < 30; i++) {
                Dog d = new Dog();
                list.add(d);
                synchronized (d) {
//                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
                }
            }
            synchronized (list) {
                list.notify();
            }
        }, "t1");
        t1.start();

        Thread t2 = new Thread(() -> {
            synchronized (list) {
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("===============> ");
            for (int i = 1; i < 30; i++) {
                Dog d = list.get(i);
//                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
                synchronized (d) {
//                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
                }
//                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
            }
        }, "t2");
        t2.start();
    }
}

